from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
# 导入 CORS
from flask_cors import CORS

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///account_book.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 初始化 CORS，允许所有来源的跨域请求
CORS(app)

class AccountRecord(db.Model):
# 定义账户记录模型的起始部分，以下将定义模型的各个字段和方法
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(10), nullable=False)  # 'income' or 'expense'
    amount = db.Column(db.Float, nullable=False)
    remark = db.Column(db.String(200))
    category = db.Column(db.String(50))
    date = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return f'<AccountRecord {self.id} {self.type} {self.amount}>'

@app.route('/records', methods=['POST'])
def add_record():
    try:
        data = request.get_json()
        record = AccountRecord(
            # 类型 ’income‘收入 ’expense‘支出
            type=data['type'],
            amount=data['amount'],
            remark=data.get('remark', ''),
            category=data.get('category'),
            date=datetime.strptime(data.get('date'), '%Y-%m-%d') if data.get('date') else None
        )
        db.session.add(record)
        db.session.commit()
        return jsonify({
            'success': True,
            'message': '添加成功',
            'error': None
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': '添加记录时发生错误',
            'error': str(e)
        }), 500

@app.route('/records', methods=['GET'])
def get_records():
    try:
        category = request.args.get('category')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        query = AccountRecord.query

        # 按日期倒序排列
        query = query.order_by(AccountRecord.date.desc())
        
        if category:
            query = query.filter(AccountRecord.category == category)
        
        if start_date and end_date:
            start = datetime.strptime(start_date, '%Y-%m-%d')
            end = datetime.strptime(end_date, '%Y-%m-%d')
            query = query.filter(AccountRecord.date.between(start, end))
        elif start_date:
            start = datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(AccountRecord.date >= start)
        elif end_date:
            end = datetime.strptime(end_date, '%Y-%m-%d')
            query = query.filter(AccountRecord.date <= end)
        
        records = query.all()
        return jsonify({
            'success': True,
            'message': '获取记录列表成功',
            'data': [
                {
                    'id': record.id,
                    'type': record.type,
                    'amount': record.amount,
                    'remark': record.remark,
                    'date': record.date.strftime('%Y-%m-%d') if record.date else None,
                    'category': record.category
                } for record in records
            ],
            'error': None
        }), 200
    except Exception as e:
        return jsonify({
            'success': False,
            'message': '获取记录列表时发生错误',
            'data': [],
            'error': str(e)
        }), 500
        
@app.route('/records/delete', methods=['POST'])
def delete_record():
    try:
        data = request.get_json()
        record = AccountRecord.query.get_or_404(data['id'])
        db.session.delete(record)
        db.session.commit()
        return jsonify({
            'success': True,
            'message': '删除成功'
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': f'删除记录时发生错误: {str(e)}'
        }), 500

@app.route('/records/batch', methods=['POST'])
def batch_add_records():
    try:
        data_list = request.get_json()
        if not isinstance(data_list, list):
            return jsonify({
                'success': False,
                'message': '请求数据必须是一个列表',
                'error': None
            }), 400

        new_records = []
        for data in data_list:
            record = AccountRecord(
                type=data['type'],
                amount=data['amount'],
                remark=data.get('remark', ''),
                category=data.get('category'),
                date=datetime.strptime(data.get('date'), '%Y-%m-%d') if data.get('date') else None
            )
            new_records.append(record)

        db.session.add_all(new_records)
        db.session.commit()
        return jsonify({
            'success': True,
            'message': '批量添加成功',
            'error': None
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': '批量添加记录时发生错误',
            'error': str(e)
        }), 500

if __name__ == '__main__':
    with app.app_context():

        # 删除所有数据库表
        # db.drop_all()

        db.create_all()
    app.run(debug=True)